/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.controller;

import admin.hibernate.model.dao.AdminLoaiSanPhamDAO;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.util.Hashtable;
import org.apache.commons.fileupload.FileItem;
import hibernate.model.dao.LoaiSanPhamDAO;
import hibernate.pojo.Loaisanpham;
import hibernate.pojo.Sanpham;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 *
 * @author phathuynh
 */
@WebServlet(name = "adminuploadfilecontroller", urlPatterns = {"/adminuploadfilecontroller"})
public class adminuploadfilecontroller extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            request.setCharacterEncoding("UTF-8");
            HttpSession session = request.getSession();
            String action = request.getParameter("action");
            if(action.equals("viewupload")){
                List<Loaisanpham> arrLoaiSanPham = AdminLoaiSanPhamDAO.AdminLayDanhSachLoaiSanPhamHQL();
                request.setAttribute("DanhSachLoaiSanPham", arrLoaiSanPham);
                request.getRequestDispatcher("Admin/pagestile/uploadfile.jsp").forward(request, response);
            }
            //<editor-fold defaultstate="collapsed" desc="Code upload">
            if(action.equals("upload")){
                Sanpham product = new Sanpham();
                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                    if (isMultipart == true) 
                    {
                        FileItemFactory factory = new DiskFileItemFactory();
                        // Create a new file upload handler
                        ServletFileUpload upload = new ServletFileUpload(factory);
                        List items = null;
                        try 
                        {
                            items = upload.parseRequest(request);
                            //The result of the parse is a List of file items,
                            //each of which implements the FileItem interface.
                        } 
                        catch (FileUploadException ex) {
                            out.println(ex);
                        }
                        Iterator iter = items.iterator();
                        Hashtable params = new Hashtable();
                        String fileName = null;
                        while (iter.hasNext()) 
                        {
                            FileItem item = (FileItem) iter.next();
                            //check if request is form
                            if (item.isFormField()) 
                            {
                                String strItem = item.getString("UTF-8");
                                String itemField = item.getFieldName();
                                params.put(itemField, strItem);
                            } 
                            else 
                            {
                                try {
                                    //Lay duong dan source cua tam hinh muon upload
                                    String itemName = item.getName();//imgtest.jpg
                                    if(itemName.equals(""))
                                    {
                                        out.print("Missing image path");
                                    }
                                    //cat duoc ten thu muc can upload
                                    String catDir = (String) params.get("cboLoaiSanPham");
                                    Loaisanpham category = LoaiSanPhamDAO.getCategoryByID(Integer.parseInt(catDir));
                                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);

                                    //Dua vao thu muc source(build) cua chuong trinh (destination)
                                    String realPath = getServletContext().getRealPath("/")
                                            + "images\\" + category.getTenTrang() + "\\" + fileName; //nen bo /build di
                                    //Lay duong dan tuong doi de insert vao csdl
                                    String insertPath = "images/" + category.getTenTrang() + "/" + fileName;
                                    
                                    
                                    //product.setAnhDaiDien(insertPath);
                                    //Tien hanh upload vao thu muc chi dinh
                                    File saveFile = new File(realPath);
                                    //Kiem tra duong dan sau xem da co tam hinh up len chua
                                    //...\build\web\images\restaurant\img.jpg
                                    item.write(saveFile);
                                    //back to upload view
                                    request.setAttribute("insertedlink", insertPath);
                                    List<Loaisanpham> arrLoaiSanPham = AdminLoaiSanPhamDAO.AdminLayDanhSachLoaiSanPhamHQL();
                                    request.setAttribute("DanhSachLoaiSanPham", arrLoaiSanPham);
                                    request.getRequestDispatcher("Admin/pagestile/uploadfile.jsp").forward(request, response);
                                } 
                                catch (Exception e) {
                                    out.println(e);
                                }
                            }
                        }//end of while
                    }//end of if
                
            }
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
